<?php
namespace Crm\Domain;

use Crm\Common\MetaData as MetaData;
use Crm\Common\Util as Util;
use Crm\Common\Pager as Pager;

class Customer
{
    protected $session; //当前用信息[上下文]
	/**
	 * ado连接。
	 * 
	 * @var object
	 * @access pdo
	 */
	public $pdo;

    public $metaData;
    public $baseCode;
    public $province_code;//省编码
    public $city_code;//城市编码
    public $borough_option;//行政区
    public $toward_option; //房屋朝向
    public $fitment_type_option; //内部装修
    public $facilities_option;//内部配套
    public $require_purpose_option;//购房目的
    public $require_type_option;  //需求类型
    public $house_level_option;//房源等级
    public $origin_option;//客户来源
    public $visit_type_option;//访问类型

    public $is_follow;//用户是否需要填写跟进
    public $is_esf_owner_super=0;//当该房源不属于自己时,判断前用户是否是该房源拥有者上级

    public function __construct()
    {
		$this->pdo = \PhalApi\DI()->pdo;

        $this->baseCode = (object)\PhalApi\DI()->config->get('basecode');
        $this->province_code = \PhalApi\DI()->config->get('app.provinceCode');//省
        $this->city_code = \PhalApi\DI()->config->get('app.cityCode');//城市

        $this->metaData = new MetaData();
        $this->borough_option = $this->metaData->getPairBaseCodeByType($this->city_code);//区域列表
        $this->toward_option   = $this->metaData->getPairBaseCodeByType(215);
        $this->fitment_type_option    = $this->metaData->getPairBaseCodeByType(219);
        $this->require_purpose_option = $this->metaData->getPairBaseCodeByType(10103);//购房目的
        $this->require_type_option = $this->metaData->getPairBaseCodeByType(10102);//需求类型
        $this->house_level_option  = $this->metaData->getPairBaseCodeByType(242);//房源等级
        $this->origin_option = $this->metaData->getPairBaseCodeByType(10105);//客户来源
        $this->visit_type_option = $this->metaData->getPairBaseCodeByType(10106);//访问类型
    }

    public function search($user){
        $this->session = (object)$user;
        $sysUser = new SysUser();

        //初始化
        $data = \PhalApi\DI()->request->getAll();
        $by = trim(isset($data["by"])?$data["by"]:'all');
        $header="";
        $page_info ="";
        $orderValue = isset($data['order']) ? $data['order'] : 'a.create_date desc,a.rating asc';
        $pageSize = isset($data['pageSize']) ? $data['pageSize'] : ' 30';
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 1;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where 1=1 and a.flag=1 ';

        $filter = array();//筛选条件
        $filter['by'] = $by;
        $filter['order'] = $orderValue;
        $page_info .="order=".$orderValue."&by=".$by."&page=".$currentPage."&";

        $sub_ids = $sysUser->getSubUserIdByUserId($this->session->user_id,0);//下属员工
        $sub_ids_str = implode(',',$sub_ids);

        //如果owner_id不等于空,则将$by设置为:all
        $owner_uid = isset($data['owner_uid'])?$data['owner_uid']:'';
        if($owner_uid!='') {$filter['by'] = 'all';}
        //视图
        switch($by) {
            //case 'today' : $where .= ' create_date='.strtotime(date('Y-m-d', time())) ; break;
            //case 'week' : $where['create_time'] =  array('gt',(strtotime(date('Y-m-d')) - (date('N', time()) - 1) * 86400)); break;
            //case 'month' : $where['create_time'] = array('gt',strtotime(date('Y-m-01', time()))); break;
            //case 'add' : $order = 'create_time desc'; break;
            //case 'update' : $order = 'update_time desc'; break;
            case 'sub' :
                if(empty($sub_ids_str)){
                    $where .= " and a.owner_uid = -1";
                }else{
                    $where .= " and a.owner_uid in (".$sub_ids_str.")";
                }
                $filter['by_val'] = '我下级的';
                break;
            //case 'deleted' : $where['is_deleted'] = 1;break;
            case 'me' :
                $where .= " and a.owner_uid=" . $this->session->user_id . " ";
                $filter['by_val'] = '我的';
                break;
            //case 'focus' : $where['customer_id'] = array('in',$focus_id);break;
            //case 'share' : $where['customer_id'] = array('in',$customerid);break;
            //case 'myshare' : $where['customer_id'] = array('in',$share_customer_ids);break;
            case 'resource':
                //房源池类型 1部门房源池 2公共房源池
                $resource_type = isset($data['resource_type'])?$data['resource_type']:'1';
                $filter['resource_type'] = $resource_type;
                $page_info .= "resource_type=".$resource_type."&";
                $warn_outdate = time()-(86400*$this->baseCode->customer['warn_outdays']);
                $danger_outdate = time()-(86400*$this->baseCode->customer['danger_outdays']);
                if($resource_type==1){
                    $dep_ids = $this->sysUser->getUserListByDepartmentId($this->session->department_id,'key');
                    $dep_ids_str = implode(',',$dep_ids);
                    //如果是管理员可以看到所有部门池客户
                    if($this->session->user_type>=4 || $this->session->user_type==1 || $this->session->isadmin){
                        $where .= " and a.log_date < " . $warn_outdate . " and a.log_date > " . $danger_outdate;
                    }else {
                        //部门房源池 不记录owner_id为0的客户,a.owner_uid=0
                        $where .= " and a.log_date < " . $warn_outdate . " and a.log_date > " . $danger_outdate;
                        if (empty($dep_ids_str)) {
                            $where .= " and a.is_locked=0 and a.owner_uid =" . $this->session->user_id;
                        } else {
                            $where .= " and a.is_locked=0 and a.owner_uid in (" . $this->session->user_id . "," . $dep_ids_str . ")";
                        }
                    }
                }else{
                    //公共房源池
                    $where .= " and a.is_locked=0 and (a.owner_uid=0 or a.log_date < ".$danger_outdate.")";
                }
                break;
            default :
                if($owner_uid!='') {
                    $where .= " and a.owner_uid =" . $owner_uid;
                    $page_info .="owner_uid=".$owner_uid."&";
                    $filter['owner_uid'] = $owner_uid;
                    $filter['by_val'] = '人员';
                }else {
                    if ($this->session->user_type >= 4) {
                        $where .= " and a.owner_uid !=0 ";
                    } else {
                        if (empty($sub_ids_str)) {
                            $where .= " and a.owner_uid =" . $this->session->user_id;
                        } else {
                            $where .= " and a.owner_uid in (" . $this->session->user_id . "," . $sub_ids_str . ")";
                        }
                    }
                    $filter['by_val'] = '全部';
                }
                break;
        }

        if($by!='resource'){
            $warn_outdate = time()-(86400*$this->baseCode->customer['warn_outdays']);
            //$where .= " and (a.log_date>".$warn_outdate." or a.is_locked=1) ";
        }

        //城市
        $where .= " and a.city_code = '".$this->city_code."'";
        $page_info .="city_code=".$this->city_code."&";

        //创建者
        $create_uid = isset($data['create_uid'])?$data['create_uid']:0;
        if($create_uid != 0){
            $where .= " and a.create_uid = ".$create_uid;
            $filter['create_uid'] = $create_uid;
            $page_info .="create_uid=".$create_uid."&";
        }
        //开始时间
        $start_date = isset($data['start_date'])?$data['start_date']:0;
        if($start_date != 0){
            $where .= " and a.create_date >= ".$start_date;
            $filter['start_date'] = $start_date;
            $page_info .="start_date=".$start_date."&";
        }
        //结束时间
        $end_date = isset($data['end_date'])?$data['end_date']:0;
        if($end_date != 0){
            $where .= " and a.create_date <= ".$end_date;
            $filter['end_date'] = $end_date;
            $page_info .="end_date=".$end_date."&";
        }

        //行政区域
        $borough = isset($data['borough'])?$data['borough']:'0';
        if($borough != '0'){
            $where .= " and a.require_borough = ".intval($borough);
            $page_info .="borough=".$borough."&";
            $filter['borough'] = $borough;
            $filter['borough_value'] = '不限';
        }else{
            $filter['borough'] = $borough;
            $filter['borough_value'] = '区域';
        }

        //需求类型  $page_info ="require_type=".$require_type."&";
        $require_type =  trim(isset($data["require_type"])?$data["require_type"]:'1010201');
        if($require_type != '0'){
            if($require_type=='1010201'){
                $header="求租";
                $price_unit = '元/月';
                $this->baseCode->price = $this->baseCode->price_option;
            }else{
                $header="求购";
                $price_unit = '万';
                $this->baseCode->price = $this->baseCode->price_total_option;
            }
            $where .= " and a.require_type = ".$require_type;
            $page_info .="require_type=".$require_type."&";
            $filter['require_type'] = $require_type;
        }
        if($by=='resource') {
            $header = "客户池";
        }

        //状态
        $status = isset($data['status'])?$data['status']:1;
        if($status>=0) {
            $where .= " and a.status = " . $status;
            $page_info .= "status=" . $status . "&";
            $filter['status'] = $status;
        }

        //价格
        $price = isset($data['price'])?$data['price']:'0';
        if($price != '0' && $price !=''){
            $_price = explode('-',$price);
            if(intval($_price[0])>0 && intval($_price[1])==0){
                $where .= " and (a.require_min_price >= " . intval($_price[0]) . ")";
            }else if(intval($_price[0])==0 && intval($_price[1])>0){
                $where .= " and (a.require_max_price <= " . intval($_price[1]) . ")";
            }else{
                $where .= " and ((a.require_min_price >= " . intval($_price[0]) . " and a.require_min_price <= " . intval($_price[1]) . ") and (a.require_max_price>=" . intval($_price[0]) . " and a.require_max_price<=" . intval($_price[1]) . "))";
            }

            $page_info .="price=".$price."&";
            $filter['price'] = $price;
            if(isset($this->baseCode->price[$filter['price']])){
                $filter['price_value'] = $this->baseCode->price[$filter['price']];
            }else{
                if($_price[0]==0){
                    $filter['price_value'] = $_price[1].$price_unit.'以下';
                }elseif($_price[1]==0){
                    $filter['price_value'] = $_price[0].$price_unit.'以上';
                }else{
                    $filter['price_value'] = $filter['price'].$price_unit;
                }
            }
        }else{
            $filter['price'] = $price;
            $filter['price_value'] = '价格';
        }

        //面积,先判断是否
        $area = isset($data['area'])?$data['area']:'0';
        if($area != '0' && $area!=''){
            $_area = explode('-',$area);
            if(intval($_area[0])>0 && intval($_area[1])==0){
                $where .= " and (a.require_min_area >= " . intval($_area[0]) . ")";
            }else if(intval($_area[0])==0 && intval($_area[1])>0){
                $where .= " and (a.require_max_area <= " . intval($_area[1]) . ")";
            }else{
                $where .= " and ((a.require_min_area >= " . intval($_area[0]) . " and a.require_min_area<=" . intval($_area[1]) . ") 
            and (a.require_max_area>=" . intval($_area[0]) . " and a.require_max_area<=" . intval($_area[1]) . "))";
            }
            $page_info .="area=".$area."&";
            $filter['area'] = $area;
            if(isset($this->baseCode->area_option[$filter['area']])){
                $filter['area_value'] = $this->baseCode->area_option[$filter['area']];
            }else{
                if($_area[0]==0){
                    $filter['area_value'] = $_area[1].'m²以下';
                }elseif($_area[1]==0){
                    $filter['area_value'] = $_area[0].'m²以上';
                }else{
                    $filter['area_value'] = $filter['area'].'m²';
                }
            }
        }else{
            $filter['area'] = $area;
            $filter['area_value'] = '面积';
        }

        //工位
        $work_station = isset($data['work_station'])?$data['work_station']:'0';
        if($work_station!= '0'){
            $_work_station = explode('-',$work_station);
            $where .= " and ((a.require_min_work_station >= ".intval($_work_station[0])." and a.require_min_work_station<=".intval($_work_station[1]).") 
            or (a.require_max_work_station>=".intval($_work_station[0])." and a.require_max_work_station<=".intval($_work_station[1])."))";
            $page_info .="work_station=".$work_station."&";
            $filter['work_station'] = $work_station;
            $filter['work_station_value'] = '不限';
        }else{
            $filter['work_station'] = $work_station;
            $filter['work_station_value'] = '工位';
        }

        //户型
        $shi = isset($data['shi'])?$data['shi']:'0';
        if($shi!= '0'){
            $where .= " and a.require_shi like '%".$shi."%'";
            $page_info .="shi=".$shi."&";
            $filter['shi'] = $shi;
            $filter['shi_value'] = '不限';
        }else{
            $filter['shi'] = $shi;
            $filter['shi_value'] = '户型';
        }

        //物业类型
        $pm_type = isset($data['pm_type'])?$data['pm_type']:'0';//20306
        if($pm_type!='0'){
            $where .= " and a.require_pm_type = ".intval($pm_type);
            $page_info .="pm_type=".$pm_type."&";
            $filter['pm_type'] = $pm_type;
            $filter['pm_type_value'] = '不限';
        }else{
            $filter['pm_type'] = $pm_type;
            $filter['pm_type_value'] = '物业类型';
        }

        //楼层
        $floor = isset($data['floor'])?$data['floor']:'0';
        if($floor != '0'){
            $_floor = explode('-',$floor);
            $page_info .="floor=".$floor."&";
            $filter['floor'] = $floor;
            if(isset($this->baseCode->floor_option[$filter['floor']])){
                $filter['floor_value'] = $this->baseCode->floor_option[$filter['floor']];
                $where .= " and ((a.require_min_floor >= ".intval($_floor[0])." and a.require_min_floor<=".intval($_floor[1]).") 
            or (a.require_max_floor>=".intval($_floor[0])." and a.require_max_floor<=".intval($_floor[1])."))";
            }else{
                if($_floor[0]!=0 && $_floor[1]==0){
                    $where .= " and (a.require_min_floor >=".intval($_floor[0]).")";
                    $filter['floor_value'] = $_floor[0].'层以上';
                }elseif($_floor[0]==0 && $_floor[1]!=0){
                    $where .= " and (a.require_max_floor <= ".intval($_floor[1]).")";
                    $filter['floor_value'] = $_floor[0].'层以下';
                }elseif($_floor[0]!=0 && $_floor[1]!=0){
                    $where .= " and ((a.require_min_floor >= ".intval($_floor[0])." and a.require_min_floor<=".intval($_floor[1]).") 
            or (a.require_max_floor>=".intval($_floor[0])." and a.require_max_floor<=".intval($_floor[1])."))";
                    $filter['floor_value'] = $filter['floor'].'层';
                }else{
                    //无输入
                }
            }
        }else{
            $filter['floor'] = $floor;
            $filter['floor_value'] = '楼层';
        }

        //装修
        $fitment_type = isset($data['fitment_type'])?$data['fitment_type']:'0';
        if($fitment_type != '0'){
            $where .= " and a.require_fitment_type = ".intval($fitment_type);
            $page_info .="fitment_type=".$fitment_type."&";
            $filter['fitment_type'] = $fitment_type;
            $filter['fitment_type_value'] = '不限';
        }else{
            $filter['fitment_type'] = $fitment_type;
            $filter['fitment_type_value'] = '装修';
        }

        //搜索
        $key = isset($data['key'])?$data['key']:'';
        if($key!=''){
            $where .= " and (a.name like '%".$key."%' or a.mobile like '".$key."%')";
            $page_info .="key=".$key."&";
            $filter['key'] = $key;
        }else{
            $filter['key'] = $key;
        }

        //记录搜索结果
        $_SESSION['referer'] = "/crm_customer/index?".$page_info;

        $select_columns = "select %s from crm_customer as a %s %s %s";
        $order = "order by $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(a.id) as count ";
        $sql = sprintf($select_columns,'a.*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);

        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key => $value) {
            $res[$key]=$this->tranCustomerInfo($value);//信息转换
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['price_unit'] = $price_unit;
        $result['page_info'] = $page_info;
        $result['splitPageStr'] = $splitPageStr;
        $result['header'] = $header;
        $result['next_page'] = $currentPage+1;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
        
    }

    /* 新增客户 */
    public function add($data,$user){
        $this->session = (object)$user;
        //if(isset($data["require_borough"]))$data["require_borough"]=implode(',',$data["require_borough"]);//区域
        //if(isset($data["require_shi"]))$data["require_shi"]=implode(',',$data["require_shi"]);//户型
        //if(isset($data["require_purpose"]))$data["require_purpose"]=implode(',',$data["require_purpose"]);//目的
        //if(isset($data["require_facilities"]))$data["require_facilities"]=implode(',',$data["require_facilities"]);//配套

        $data['log_date'] = time();
        $data['create_uid'] = $this->session->user_id;
        $data['write_uid'] = $this->session->user_id;
        $data['owner_uid'] = $this->session->user_id;

        //todo: 设置城市
        $data['city_code']=$this->session->city_code;

        $rlt = $this->pdo->add($data,'crm_customer');
        if($rlt){
            $sysLog = new SysLog();
            $sysLog->actionLog($rlt,$this->session->user_id,'新增客源','crm_customer','add');//系统日志

            $result['id'] = $rlt;
            $result['msg'] = '新增成功!';
        }else{
            $result['id'] = $rlt;
            $result['msg'] = '新增失败!';
        }
        return $result;
    }

    /* 更新客户 */
    public function update($data,$user){
        $id = isset($data['customer_id'])?$data['customer_id']:0;
        if($id>0){
            $sysLog = new SysLog();
            $sysLog->actionLog($id,$this->session->user_id,"编辑客户",'crm_customer','update');
            $rlt = $this->pdo->update($data,'crm_customer','id='.$id.' and owner_uid='.$user['user_id']);
            if($rlt){
                $result['rlt'] = 1;
                $result['msg'] = '修改成功!';
            }else{
                $result['rlt'] = 0;
                $result['msg'] = '修改失败!';
            }
        }else{
            $result['rlt'] = 0;
            $result['msg'] = '非法房源数据!';
        }
        return $result;
    }

    /* 获取用户的客源列表 */
    public function getCustomerListByUserId($user_id,$currentPage=0){
        $pageSize = 30;
        $offset = 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $order = "order by a.create_date desc ";
        $limit = "limit {$offset},{$pageSize}";
        $sql = "select a.* from crm_customer as a 
                where a.owner_uid = {$user_id} and a.flag=1 ".$order." ".$limit;
        $sqlcnt = "select count(*) as cnt from crm_customer where owner_uid = {$user_id} and flag=1";
        $rlt = $this->pdo->getAll($sql);
        foreach ($rlt as $key=>$Info){
            $rlt[$key]['require_type_val'] = '求租';
            if ($Info['require_type'] == 1) {
                $rlt[$key]['require_type_val'] = "求购";
            }
            $rlt[$key]['scr_mobile'] = substr($Info['mobile'],0,3)."********";
            $rlt[$key]['sex_val'] = $this->baseCode->sex_option[$Info['sex']];
            $rlt[$key]['create_date_val'] = date('Y-m-d H:i',$Info['create_date']);
        }
        $data['list'] = $rlt;
        $cnt = $this->pdo->getRow($sqlcnt);
        $data['cnt'] = $cnt['cnt'];
        $data['page'] = $currentPage;
        return $data;
    }

    /* 根据ID获取客户姓名 */
    public function getCustomerNameById($customer_id){
        $sql = "select a.name from crm_customer as a where a.id={$customer_id}";
        $Info = $this->pdo->getRow($sql);
        return $Info['name'];
    }

    /* 根据ID获取客户来源 */
    public function getOriginById($customer_id){
        $sql = "select a.origin from crm_customer as a where a.id={$customer_id}";
        $Info = $this->pdo->getRow($sql);
        if(!empty($Info['origin'])){
            return $this->origin_option[$Info['origin']];
        }else{
            return false;
        }
    }

    /* 根据ID获取客户详情 */
    public function getCustomerInfoById($customer_id,$type='detail'){
        $sql = "select a.* from crm_customer as a where a.id={$customer_id}";
        //初始数据
        $Info = $this->pdo->getRow($sql);
        if($type=='detail') {
            $Info = $this->tranCustomerInfo($Info);
        }
        return $Info;
    }

    /* 将客户信息转换为详细信息 */
    public function tranCustomerInfo($Info){
        $Info['price_uitl'] = ($Info['require_type']==1010201)?"元/月":"万元";
        $Info['project_title'] = ($Info['require_pm_type']==20306)?"楼盘":"小区"; //todo 此处什么意思呢
        //根据物业类型处理相关数据
        switch ($Info['require_pm_type']){
            case '20306':
                $this->facilities_option      = $this->metaData->getPairBaseCodeByType(232);
                break;
            default:
                $this->facilities_option      = $this->metaData->getPairBaseCodeByType(217);
                break;
        }
        $Info['require_borough'] = explode(",", $Info['require_borough']);
        $Info['require_borough_val'] = $this->tranMateData($Info['require_borough'],$this->borough_option);
        $Info['require_purpose'] = explode(",", $Info['require_purpose']);
        $Info['require_purpose_val'] = $this->tranMateData($Info['require_purpose'],$this->require_purpose_option);
        $Info['require_facilities'] = explode(",", $Info['require_facilities']);
        $Info['require_facilities_val'] = $this->tranMateData($Info['require_facilities'],$this->facilities_option);
        $Info['require_fitment_type_val'] = $this->fitment_type_option[$Info['require_fitment_type']];
        $Info['require_type_val'] = $this->require_type_option[$Info['require_type']];
        $Info['status_val'] = $this->baseCode->customer_status_option[$Info['status']];
        $Info['status_color'] = $this->tranStatusColor($Info['status']);
        $Info['scr_mobile'] = substr($Info['mobile'], 0, 3) . "*******";
        $Info['require_shi'] = explode(",", $Info['require_shi']);

        //性别处理
        if($Info['sex']==1){
            $Info['avtor'] = '-m2';
            $Info['msmr'] = '先生';
        }else{
            $Info['avtor'] = '-w3';
            $Info['msmr'] = '女士';
        }

        //客户等级
        $Info['rating_val'] = $this->baseCode->rating_option[$Info['rating']];

        //创建时间
        $Info['create_date_long']=date('Y-m-d H:i:s', $Info['create_date']);
        $Info['create_date_short']=date('Y-m-d', $Info['create_date']);

        //获取录入人员名称
        $user = $this->pdo->getRow("select user_name,true_name,is_admin from sys_user where id='{$Info['create_uid']}' and flag=1");
        $Info['create_name'] = $user['true_name'];

        //负责人员名称
        $user = $this->pdo->getRow("select a.user_name,a.true_name,a.is_admin,b.org_name from sys_user as a left join sys_orgstruct as b on a.department_id=b.id where a.id='{$Info['owner_uid']}' and a.flag=1");
        $Info['owner_name'] = $user['true_name'];
        $Info['org_name'] = $user['org_name'];

        //物业
        $Info['require_pm_type_val'] = $this->baseCode->pm_type_option[$Info['require_pm_type']];

        //获取商圈
        $business_region = explode(',',$Info['require_business_region']);
        if(count($business_region)>0) {
            foreach ($business_region as $code){
                $Info['business_region'] .= $this->metaData->getNameByCode($code).'、';
            }
            $Info['business_region'] = Util::msubstr($Info['business_region'],0,-1);
        }
        //获取小区
        $project_ids = explode(',',$Info['require_project_id']);
        if(count($project_ids)>0) {
            $project = new Project();
            foreach ($project_ids as $code){
                $Info['project_name'] .= $project->getNameById($code).'、';
            }
            $Info['project_name'] = Util::msubstr($Info['project_name'],0,-1);
        }

        //统计带看
        $sql = "select count(*) as cnt from crm_visit where flag=1 and customer_id={$Info['id']}";
        $visit_cnt = $this->pdo->getRow($sql);
        $Info['visit_cnt'] =  $visit_cnt['cnt'];

        //统计跟进日志
        $sql = "select count(*) as cnt from crm_r_customer_log where customer_id={$Info['id']}";
        $log_cnt = $this->pdo->getRow($sql);
        $Info['log_cnt'] =  $log_cnt['cnt'];

        //最后一次跟进 通过日志表获取最后一次跟进日期
        /*
        $sql = "select a.id,a.log_id,a.customer_id,b.create_date from crm_r_customer_log as a LEFT JOIN crm_log as b on a.log_id=b.id where a.customer_id={$Info['id']} and b.flag=1 order by a.id desc limit 0,1";
        $log = $this->pdo->getRow($sql);
        if(isset($log['create_date'])) {
            $Info['out_time'] = time()-$log['create_date'];
            //$Info['log_create_date'] = Util::formatDate($log['create_date']).'跟进';
            $Info['log_create_date_val'] = date('Y-m-d H:i', $log['create_date']);
        }else{
            $Info['out_time'] = time()-$Info['create_date'];
            $Info['log_create_date'] = '没有跟进信息';
            $Info['log_create_date_val'] = $Info['log_create_date'];
        }
        */
        if($Info['log_date']==$Info['create_date']) {
            $Info['out_time'] = 0;
            $Info['log_date_val'] = '没有跟进信息';
        }else{
            $Info['out_time'] = time()-$Info['log_date'];
            $Info['log_date_val'] = date('Y-m-d H:i', $Info['log_date']);
        }
        return $Info;
    }

    /* 获取客户看房记录 */
    public function getCustomerVisit(){
        $data = \PhalApi\DI()->request->getAll();
        $sysUser = new SysUser();
        $esf = new Esf();
        $project = new Project();

        $by = trim(isset($data["by"])?$data["by"]:'all');
        $page_info = "";
        $orderField = isset($data['sort']) ? $data['sort'] : 'a.id';
        $orderValue = isset($data['flag']) ? $data['flag'] : 'desc';
        $pageSize = 20;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;

        $where = 'where a.flag=1 ';
        switch ($by) {
            //case 'today' : $where .= ' create_date='.strtotime(date('Y-m-d', time())) ; break;
            //case 'week' : $where['create_time'] =  array('gt',(strtotime(date('Y-m-d')) - (date('N', time()) - 1) * 86400)); break;
            //case 'month' : $where['create_time'] = array('gt',strtotime(date('Y-m-01', time()))); break;
            //case 'add' : $order = 'create_time desc'; break;
            //case 'update' : $order = 'update_time desc'; break;
            //case 'sub' : $where['owner_role_id'] = array('in',implode(',', $below_ids)); break;
            //case 'deleted' : $where['is_deleted'] = 1;break;
            case 'me' :
                $where .= "and a.create_uid=".$this->session->user_id." ";
                $page_info .= "by=".$by."&";
                break;
            //case 'focus' : $where['customer_id'] = array('in',$focus_id);break;
            //case 'share' : $where['customer_id'] = array('in',$customerid);break;
            //case 'myshare' : $where['customer_id'] = array('in',$share_customer_ids);break;
            default :
                break;
        }

        //客户,存在客户ID表示查询该客户看房记录
        $customer_id = isset($data['customer_id'])?$data['customer_id']:0;
        if($customer_id != 0){
            $where .= " and a.customer_id = ".$customer_id;
            $filter['customer_id'] = $customer_id;
            $page_info .="id=".$customer_id."&";
        }

        //创建者
        $create_uid = isset($data['create_uid'])?$data['create_uid']:0;
        if($create_uid != 0){
            $where .= " and a.create_uid = ".$create_uid;
            $filter['create_uid'] = $create_uid;
            $page_info .="create_uid=".$create_uid."&";
        }
        //开始时间
        $start_date = isset($data['start_date'])?$data['start_date']:0;
        if($start_date != 0){
            $where .= " and a.create_date >= ".$start_date;
            $filter['start_date'] = $start_date;
            $page_info .="start_date=".$start_date."&";
        }
        //结束时间
        $end_date = isset($data['end_date'])?$data['end_date']:0;
        if($end_date != 0){
            $where .= " and a.create_date <= ".$end_date;
            $filter['end_date'] = $end_date;
            $page_info .="end_date=".$end_date."&";
        }

        $select_columns = "select %s from crm_visit as a %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(a.id) as cnt ";
        $fields = 'a.*';
        $sql = sprintf($select_columns,$fields,$where,$order,$limit);
        $sqlcount = sprintf($select_columns, $count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['cnt'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();

        //关联信息
        foreach ($res as $key=>$item){
            $sql = "select user_name,true_name,headimgurl from sys_user where id={$item['create_uid']}";
            $res[$key]['user'] = $this->pdo->getRow($sql);
            $res[$key]['customer_name'] = $this->getCustomerNameById($item['customer_id']);

            if($item['type']=='fc_esf') {
                $sql = "select b.id as esf_id,b.project_id,b.house_type,b.build_no,b.unit_no,b.house_no,b.pm_type,b.ting,b.shi,b.img_path,b.house_level,b.house_category,b.toward,b.fitment_type,b.current_floor,b.total_floor from fc_esf as b where b.id=".$item['action_id'];
                $esfInfo = $this->pdo->getRow($sql);
                $res[$key]['current_floor'] = $esfInfo['current_floor'];
                $res[$key]['total_floor'] = $esfInfo['total_floor'];
                $res[$key]['house_type'] = $esfInfo['house_type'];
                $res[$key]['esf_id'] = $esfInfo['esf_id'];
                $res[$key]['huxing'] = $esf->tranHuxing($esfInfo['ting'], $esfInfo['shi']);
                $res[$key]['address'] = $esf->tranAddress($esfInfo['build_no'], $esfInfo['unit_no'], $esfInfo['house_no']);
                $res[$key]['img_path'] = str_replace('.', '_s.', $esfInfo['img_path']);
                $res[$key]['house_level'] = $this->house_level_option[$esfInfo['house_level']];
                if ($esfInfo['project_id'] > 0) {
                    //项目名称
                    $res[$key]['project_name'] = $project->getNameById($esfInfo['project_id']);
                }
                $res[$key]['fitment_type_val'] = isset($this->fitment_type_option[$esfInfo['fitment_type']]) ? $this->fitment_type_option[$esfInfo['fitment_type']] : '';
                $res[$key]['toward_val'] = ($esfInfo['toward']!='')?$this->toward_option[$esfInfo['toward']]:'';
                $res[$key]['pm_type_val'] = $this->baseCode->pm_type_option[$esfInfo['pm_type']];
                $res[$key]['label'] = ($item['visit_type']==1010601)?'面谈':'带看';
                $res[$key]['label_class'] = ($item['visit_type']==1010601)?'weui-badge f-white bg-blue mrx':'weui-badge f-white bg-orange mrx';
                $res[$key]['house_type_val'] = ($esfInfo['house_type']==1)?'出租':'出售';
                $res[$key]['house_type_class'] = ($esfInfo['house_type']==1)?'weui-badge f-white bg-green mrx':'weui-badge f-white bg-orange mrx';
            }else{
                //到访项目
                $projectInfo = $project->getProjectInfo($item['action_id']);
                $res[$key]['project_name'] = $projectInfo['name'];
                $res[$key]['project_id'] = $projectInfo['id'];
                $res[$key]['address'] = $projectInfo['address'];
                $res[$key]['label'] = ($item['visit_type']==1010601)?'面谈':'带看';
                $res[$key]['label_class'] = ($item['visit_type']==1010601)?'weui-badge f-white bg-blue mrx':'weui-badge f-white bg-orange mrx';
            }

            //陪看人员
            if($item['together_uid']!='') {
                $_together_uid = explode(',',$item['together_uid']);
                foreach ($_together_uid as $val) {
                    if($val!='') {
                        $together = $sysUser->getUserNameById($val);
                        $res[$key]['together_name'] .= $together['true_name'] . ',';
                    }
                }
            }else{
                $res[$key]['together_name'] = '无';
            }
            if($item['visit_date']>0){
                $res[$key]['visit_date'] = date('Y-m-d H:i:s',$item['visit_date']);
            }else{
                $res[$key]['visit_date'] ='';
            }
        }

        $result['list'] = $res;
        $result['filter'] = $filter;
        $result['cnt'] = $recordCount;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        $result['pageStr'] = $splitPageStr;
        return $result;
    }

    /* 获取客户跟进日志 */
    public function getCustomerLog(){
        $data = \PhalApi\DI()->request->getAll();
        $id = intval(isset($data["customer_id"])?$data["customer_id"]:0);
        $by = trim(isset($data["by"])?$data["by"]:'all');
        $page_info = "customer_id=".$id."&";
        $orderField = isset($data['sort']) ? $data['sort'] : 'a.id';
        $orderValue = isset($data['flag']) ? $data['flag'] : 'desc';
        $pageSize = 5;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 1;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where b.flag=1 and a.customer_id='.$id.' ';
        switch ($by) {
            //case 'today' : $where .= ' create_date='.strtotime(date('Y-m-d', time())) ; break;
            //case 'week' : $where['create_time'] =  array('gt',(strtotime(date('Y-m-d')) - (date('N', time()) - 1) * 86400)); break;
            //case 'month' : $where['create_time'] = array('gt',strtotime(date('Y-m-01', time()))); break;
            //case 'add' : $order = 'create_time desc'; break;
            //case 'update' : $order = 'update_time desc'; break;
            //case 'sub' : $where['owner_role_id'] = array('in',implode(',', $below_ids)); break;
            //case 'deleted' : $where['is_deleted'] = 1;break;
            case 'me' :
                $where .= "and b.create_uid=".$this->session->user_id." ";
                $page_info .= "by=".$by."&";
                break;
            //case 'focus' : $where['customer_id'] = array('in',$focus_id);break;
            //case 'share' : $where['customer_id'] = array('in',$customerid);break;
            //case 'myshare' : $where['customer_id'] = array('in',$share_customer_ids);break;
            default :
                break;
        }
        $select_columns = "select %s from crm_r_customer_log as a LEFT JOIN crm_log as b on a.log_id=b.id %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(a.id) as cnt ";
        $sql = sprintf($select_columns,'b.*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns, $count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['cnt'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();
        //关联用户信息,生成视图
        foreach ($res as $key=>$item){
            $sql = "select user_name,true_name,headimgurl from sys_user where id={$item['create_uid']}";
            $res[$key]['user'] = $this->pdo->getRow($sql);
            $res[$key]['create_date'] = Util::formatDate($item['create_date']);
        }
        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        $result['pageStr'] = $splitPageStr;

        return $result;
    }

    /* 返回拥有该客户的拥有者 */
    public function getCustomerByMobile($mobile){
        //判断电话是否合法
        $sql = "select id,name,owner_uid from crm_customer where mobile={$mobile}";
        $rlt['data'] = $this->pdo->getAll($sql);
        $rlt['cnt'] = count($rlt['data']);
        return $rlt;
    }

    /* 获取客户源池 客户 */
    public function getCustomer($customer_id){
        $Info = $this->getCustomerInfoById($customer_id,'base');

        $isOut = $this->isOutdate($Info['log_date']);
        //只有房源池中房源,才可以被获取
        if($Info['owner_uid']==0 || $isOut){
            $sql = "update crm_customer set owner_uid=".$this->session->user_id.",log_date=".time()." where id=".$customer_id;
            $rlt = $this->pdo->doSql($sql);
            if ($rlt) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }
    }

    /* 是否为客户池客户 */
    public function isOutdate($curDate,$type='warn'){
        //如果为客户池客户
        if($type=='warn') {
            $warn_outdate = time() - (86400 * $this->baseCode->customer->warn_outdays);
            $is_out = ($curDate < $warn_outdate) ? 1 : 0;
        }else{
            $danger_outdate = time()-(86400*$this->baseCode->customer->danger_outdays);
            $is_out = ($curDate < $danger_outdate) ? 1 : 0;
        }
        return $is_out;
    }

    /* 返回自己是否拥有该客户 */
    public function isHaveCustomerByUserId($mobile,$user_id){
        $sql = "select count(*) as cnt from crm_customer where mobile={$mobile} and owner_uid={$user_id}";
        $rlt = $this->pdo->getRow($sql);
        if($rlt['cnt']>0){
            return true;
        }else{
            return false;
        }
    }

    /* 返回同队是否有该客户 */
    public function isHaveCustomerByDepartmentId($mobile,$DepartmentId){
        $sysUser = new sysUser();
        $role_ids = $sysUser->getUserListByDepartmentId($DepartmentId,'string');
        $role_ids_str = implode(',',$role_ids);
        //判断本部门是否有该电话
        $sql = "select count(*) as cnt from crm_customer where mobile={$mobile} and owner_uid in ({$role_ids_str})";
        $rlt = $this->pdo->getRow($sql);
        if($rlt['cnt']>0){
            return true;
        }else{
            return false;
        }
    }

    /* 更新客户状态 */
    public function updateCustomerStatus($customer_id,$status){
        $sql = "update crm_customer set status={$status} where id={$customer_id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 更新客户等级 */
    public function updateCustomerRating($customer_id,$rating){
        $sql = "update crm_customer set rating='{$rating}' where id={$customer_id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 锁定客户 */
    public function locked($customer_id,$is_locked){
        if(intval($customer_id)>0 && !empty($is_locked)){
            $sql = "update crm_customer set is_locked=".$is_locked." where id=".$customer_id;
            $rlt = $this->pdo->doSql($sql);
            if ($rlt) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }
    }

    /* 获取最近需要填写跟进记录 */
    public function getNeedFollow(){
        $sql = "select * from sys_action_log where module='crm_customer' and action='showtel' and status=0 and create_uid=".$this->session->user_id;
        $rlt = $this->pdo->getRow($sql);
        return $rlt;
    }

    /* 判断是否有需要填写的跟进记录 */
    public function isNeedFollow(){
        $sql = "select count(*) as cnt from sys_action_log where module='crm_customer' and action='showtel' and status=0 and create_uid=".$this->session->user_id;
        $rlt = $this->pdo->getRow($sql);
        return $rlt['cnt'];
    }

    /* 转换简直为中文 */
    private function tranMateData($ids,$mateData){
        $purpose = '';
        foreach ($ids as $id){
            $purpose .= $mateData[$id].'、';
        }
        $purpose = Util::msubstr($purpose,0,-1);
        return $purpose;
    }

    /* 状态颜色转变 */
    private function tranStatusColor($status){
        switch($status){
            case '1'://有效
                $color ='blue';
                break;
            case '4'://签约
                $color ='green';
                break;
            case '2'://到访
                $color ='orange';
                break;
            case '3'://认购/租
                $color ='glod';
                break;
            case '5'://结佣
                $color ='red';
                break;
            case '0'://无效
                $color ='black';
                break;
            case '9'://待审核
                $color ='black';
                break;
            default:
                $color ='blue';
                break;
        }
        return $color;
    }

}

